/**
 * Mock 功能测试脚本
 * 用于验证所有 Mock 功能是否正常工作
 */

import api from './request.js';

// 测试结果记录
const testResults = {
  passed: 0,
  failed: 0,
  tests: []
};

// 添加测试结果
const addTestResult = (name, success, error = null) => {
  const result = { name, success, error, timestamp: new Date().toISOString() };
  testResults.tests.push(result);
  
  if (success) {
    testResults.passed++;
    console.log(`✅ ${name} - 通过`);
  } else {
    testResults.failed++;
    console.log(`❌ ${name} - 失败: ${error}`);
  }
};

// 测试认证模块
const testAuthModule = async () => {
  console.log('\n🔐 测试认证模块...');
  
  try {
    // 测试登录
    const loginResponse = await api.post('/auth/login', {
      username: 'testuser',
      password: '123456'
    });
    addTestResult('用户登录', !!loginResponse.token);
    
    // 测试获取当前用户
    const userResponse = await api.get('/auth/current-user');
    addTestResult('获取当前用户', !!userResponse.name);
    
    // 测试登出
    const logoutResponse = await api.post('/auth/logout');
    addTestResult('用户登出', logoutResponse.code === 200);
    
  } catch (error) {
    addTestResult('认证模块测试', false, error.message);
  }
};

// 测试用户模块
const testUserModule = async () => {
  console.log('\n👥 测试用户模块...');
  
  try {
    // 测试获取用户列表
    const usersResponse = await api.get('/users', {
      params: { page: 1, size: 5 }
    });
    addTestResult('获取用户列表', Array.isArray(usersResponse.data || usersResponse));
    
    // 测试创建用户
    const newUser = {
      username: `test_${Date.now()}`,
      name: '测试用户',
      email: `test${Date.now()}@example.com`,
      phone: '13800138000'
    };
    const createResponse = await api.post('/users', newUser);
    addTestResult('创建用户', !!createResponse.id);
    
    // 测试获取用户统计
    const statsResponse = await api.get('/users/stats');
    addTestResult('获取用户统计', !!statsResponse.total);
    
  } catch (error) {
    addTestResult('用户模块测试', false, error.message);
  }
};

// 测试案件模块
const testCaseModule = async () => {
  console.log('\n📋 测试案件模块...');
  
  try {
    // 测试获取案件列表
    const casesResponse = await api.get('/cases', {
      params: { page: 1, size: 5 }
    });
    addTestResult('获取案件列表', Array.isArray(casesResponse.data || casesResponse));
    
    // 测试创建案件
    const newCase = {
      title: `测试案件${Date.now()}`,
      description: '这是一个测试案件',
      category: '民事纠纷',
      applicantName: '测试申请人',
      applicantPhone: '13800138000'
    };
    const createResponse = await api.post('/cases', newCase);
    addTestResult('创建案件', !!createResponse.id);
    
    // 测试更新案件状态
    if (createResponse.id) {
      const updateResponse = await api.patch(`/cases/${createResponse.id}/status`, {
        status: 1
      });
      addTestResult('更新案件状态', updateResponse.status === 1);
    }
    
    // 测试获取案件统计
    const statsResponse = await api.get('/cases/stats');
    addTestResult('获取案件统计', !!statsResponse.total);
    
  } catch (error) {
    addTestResult('案件模块测试', false, error.message);
  }
};

// 测试律师模块
const testLawyerModule = async () => {
  console.log('\n⚖️ 测试律师模块...');
  
  try {
    // 测试获取律师列表
    const lawyersResponse = await api.get('/lawyers', {
      params: { page: 1, size: 5 }
    });
    addTestResult('获取律师列表', Array.isArray(lawyersResponse.data || lawyersResponse));
    
    // 测试创建律师
    const newLawyer = {
      username: `lawyer_${Date.now()}`,
      name: '测试律师',
      email: `lawyer${Date.now()}@example.com`,
      phone: '13900139000',
      specialties: ['民事纠纷'],
      experience: 5
    };
    const createResponse = await api.post('/lawyers', newLawyer);
    addTestResult('创建律师', !!createResponse.id);
    
    // 测试获取律师工作台
    if (createResponse.id) {
      const dashboardResponse = await api.get(`/lawyers/${createResponse.id}/dashboard`);
      addTestResult('获取律师工作台', !!dashboardResponse.lawyer);
    }
    
    // 测试获取律师统计
    const statsResponse = await api.get('/lawyers/stats');
    addTestResult('获取律师统计', !!statsResponse.total);
    
  } catch (error) {
    addTestResult('律师模块测试', false, error.message);
  }
};

// 测试错误处理
const testErrorHandling = async () => {
  console.log('\n⚠️ 测试错误处理...');
  
  try {
    // 测试不存在的接口
    await api.get('/non-existent-endpoint');
    addTestResult('404错误处理', false, '应该返回404错误');
  } catch (error) {
    addTestResult('404错误处理', error.message.includes('404') || error.message.includes('未定义'));
  }
  
  try {
    // 测试登录失败
    await api.post('/auth/login', {
      username: 'wronguser',
      password: 'wrongpass'
    });
    addTestResult('登录失败处理', false, '应该返回401错误');
  } catch (error) {
    addTestResult('登录失败处理', error.message.includes('用户名或密码错误'));
  }
};

// 测试数据生成
const testDataGeneration = async () => {
  console.log('\n🎲 测试数据生成...');
  
  try {
    // 测试用户数据生成
    const usersResponse = await api.get('/users', {
      params: { page: 1, size: 10 }
    });
    const users = usersResponse.data || usersResponse;
    
    if (users.length > 0) {
      const user = users[0];
      const hasValidData = user.name && user.email && user.phone;
      addTestResult('用户数据生成', hasValidData);
    }
    
    // 测试案件数据生成
    const casesResponse = await api.get('/cases', {
      params: { page: 1, size: 10 }
    });
    const cases = casesResponse.data || casesResponse;
    
    if (cases.length > 0) {
      const caseItem = cases[0];
      const hasValidData = caseItem.title && caseItem.category && caseItem.applicantName;
      addTestResult('案件数据生成', hasValidData);
    }
    
    // 测试律师数据生成
    const lawyersResponse = await api.get('/lawyers', {
      params: { page: 1, size: 10 }
    });
    const lawyers = lawyersResponse.data || lawyersResponse;
    
    if (lawyers.length > 0) {
      const lawyer = lawyers[0];
      const hasValidData = lawyer.name && lawyer.specialties && lawyer.experience;
      addTestResult('律师数据生成', hasValidData);
    }
    
  } catch (error) {
    addTestResult('数据生成测试', false, error.message);
  }
};

// 运行所有测试
const runAllTests = async () => {
  console.log('🚀 开始 Mock 功能测试...');
  console.log('=' * 50);
  
  await testAuthModule();
  await testUserModule();
  await testCaseModule();
  await testLawyerModule();
  await testErrorHandling();
  await testDataGeneration();
  
  // 输出测试结果
  console.log('\n' + '=' * 50);
  console.log('📊 测试结果汇总:');
  console.log(`✅ 通过: ${testResults.passed}`);
  console.log(`❌ 失败: ${testResults.failed}`);
  console.log(`📈 成功率: ${((testResults.passed / (testResults.passed + testResults.failed)) * 100).toFixed(1)}%`);
  
  if (testResults.failed === 0) {
    console.log('\n🎉 所有测试通过！Mock 功能正常工作。');
  } else {
    console.log('\n⚠️ 部分测试失败，请检查相关功能。');
    console.log('\n失败的测试:');
    testResults.tests
      .filter(test => !test.success)
      .forEach(test => {
        console.log(`  - ${test.name}: ${test.error}`);
      });
  }
  
  return testResults;
};

// 导出测试函数
export { runAllTests, testResults };

// 如果直接运行此文件，执行测试
if (import.meta.env.DEV) {
  // 延迟执行，确保 Mock 已加载
  setTimeout(() => {
    runAllTests();
  }, 1000);
} 